package com.hae.shop.common.util;

import com.hae.shop.common.util.annotation.MemberOf;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * 限定参数只能取值的校验规则
 */
public class MemberValidator implements ConstraintValidator<MemberOf, String> {

    private String[] allowValues;

    @Override
    public void initialize(MemberOf memberOf) {
        this.allowValues = memberOf.member();
    }

    /**
     * 遍历设定的member字符串集合，如果为空或null则直接失败
     * @param value
     * @param constraintValidatorContext
     * @return
     */
    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        boolean result = false;
        if (null != allowValues && allowValues.length >0) {
            for (String str: allowValues) {
                if (str.equals(value)) {
                    result = true;
                    break;
                }
            }
        }
        return result;
    }
}
